import javax.mail.Session
import javax.mail.Store
import javax.mail.Folder
import de.motsangria.mail.MailAuthenticator
import javax.mail.Flags

class MailReaderService {

  boolean transactional = false

  private getMailProperties = {
    Properties props = new Properties()
    props.setProperty("mail.imap.host", "imap.gmail.com")
    props.setProperty("mail.imap.user", 'motsangria@googlemail.com')
    props.setProperty("mail.imap.password", 'v8ESo5jH3Jg8zg2W3hgZrb')
    props.setProperty("mail.imap.port", "993")
    props.setProperty("mail.imap.auth", "true")
    return props
  }

  public void getEMails() {

    Properties props = getMailProperties()
    Session session = Session.getInstance(props, null)
    session.setDebug(false)
    Store store = session.getStore('imaps')

    try {
      store.connect(props.getProperty('mail.imap.host'), props.getProperty('mail.imap.user'), props.getProperty('mail.imap.password'))
    } catch (Exception  e) {
      log.warn ("MailReaderService is unable to connect to mailserver. Will try again later.")
    }

    if (store.isConnected()) {
      Folder folder = store.getFolder('INBOX')
      folder.open(Folder.READ_WRITE)

      def emailAddresses = EmailAddress.list()
      def messages = folder.getMessages()
      messages.eachWithIndex {javax.mail.Message mailMessage, i ->
        def emailAddress = null
        mailMessage.from.each{
          String tmpAddress = stripMailAddress(it.toString())
          emailAddress = emailAddresses.find {it.email == tmpAddress}
        }
        if (emailAddress) {
          String text = mailMessage.subject
          if (text.length() > 255) text = "${text.substring(0,249)} [...]"
          def msg = new Message(user: emailAddress.user, content: text, medium: 'MoTS Mail Aggregator', dateCreated: mailMessage.sentDate)
          if (msg.validate() && msg.save()) {
            log.info ("New Mail Message from: ${mailMessage.from}, identified mail address: ${emailAddress}, user: ${emailAddress?.user}, subject: ${mailMessage.subject}, sent: ${mailMessage.sentDate}")
          } else {
            log.error ("Error creating new message: ${msg.errors}")
          }
        } else {
          log.warn ("New Mail Message with unidentified sender: ${mailMessage.from}, subject: ${mailMessage.subject}, sent: ${mailMessage.sentDate}")
        }
        mailMessage.setFlag(Flags.Flag.DELETED, true)
      }

      folder.close(true);
      store.close();
    }
  }

  def stripMailAddress = {String addr ->
    String returnString = addr
    returnString = returnString.replaceAll('.*<', '')
    returnString = returnString.replaceAll('>.*', '')
    return returnString.toLowerCase()
  }
}
